﻿using System;
using System.Web;
using System.Text;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using EpisodeWizard.Core;


namespace MyPlugins
{

    /// <summary>
    /// Implements a plugin to get info from "epguides"
    /// </summary>
	public class Epguides : QueryPluginCached
    {

        /// <summary>
        /// The name of this engine
        /// </summary>
        override public string Name
        {
            get
            {
                return "Epguides";
            }
        }

        /// <summary>
        /// The description of this engine
        /// </summary>
        override public string Description
        {
            get
            {
                return "Retrieves episode information from http://www.epguides.com";
            }
        }


        /// <summary>
        /// The URL of the Epguides website
        /// </summary>
        private string EpguidesWebsite = "http://epguides.com";

		private int NbBytesReceived = 0;


		/// <summary>
		/// Initialize the plugin
		/// </summary>
		public override void Initialize()
		{
			NbBytesReceived = 0;

			for (char c = 'a'; c < 'z'; ++c)
			{
				int Percent = (int)((c - 'a') / 26.0 * 100.0);
				OnInitializeProgress(Percent, "Epguides - Retrieving shows : " + Char.ToUpper(c), "Total " + (NbBytesReceived / 1024) + " KB");
				RetrieveShowList(c);
			}
		}


		/// <summary>
		/// Gets the list of shows for a particular letter (A-Z)
		/// </summary>
		private void RetrieveShowList(char Letter)
		{
			// Shows are listed this way :
			// <li><a href="../HettyWainthroppInvestigates/">Hetty Wainthropp Investigates</a>
			// <li><b><a href="../Heroes/">Heroes</a></b></li>

			string URL = EpguidesWebsite + "/menu" + Char.ToLower(Letter);
			string PageShows = HttpFetcher.Fetch(URL);
			NbBytesReceived += PageShows.Length;

			string Start = "<a href=\"../";
			string Middle = "/\"\\>";
			string End = "</a\\>";

			MatchCollection Collection = Regex.Matches(PageShows, "\\" + Start + "(?<ShowId>.*?)" + "\\" + Middle + "(?<ShowName>.*?)" + "\\" + End);
			foreach (Match M in Collection)
			{
				QueryPluginCached.CachedShow Show = new QueryPluginCached.CachedShow();
				Show.ID = M.Groups["ShowId"].Value.ToLower();
				Show.Name = M.Groups["ShowName"].Value.ToLower();
				Show.Name = System.Web.HttpUtility.HtmlDecode(Show.Name);

				bool RealShow = (Show.Name.Length > 1) && (Show.Name.IndexOf("epguides.com") == -1);
				if (RealShow)
				{
					try
					{
						// Remove Epguides comments from the names
						Show.Name = Show.Name.Replace("[anim]", "").Replace("[on hiatus]", "");
						Debug.WriteLine("Adding " + Show.Name);
						CachedShows.Add(Show.Name, Show);
					}
					catch (ArgumentException)
					{
						Debug.WriteLine("Duplicate show " + Show.Name);
						continue;
					}
				}
			}			
		}


		/// <summary>
		/// Gets the list of episodes for a show and adds them to the cache
		/// </summary>
		protected override void AddShowToCache(CachedShow Show)
		{
			string PageShow = HttpFetcher.Fetch(EpguidesWebsite + "/" + Show.ID);
			Console.WriteLine(PageShow);

			// The show page is like this :
			//
			//							  Original
			//  Episode #     Prod #      Air Date   Titles
			// _____ ______ ___________  ___________ ___________________________________________
			//
			// * 
			// Pilot / Season X / Special
			//
			//
			//  3.   1- 3        103      9 Oct 06   <a target="_blank" href="http://www.tv.com/heroes/one-giant-leap/episode/859129/summary.html">One Giant Leap</a>
			//

			string Number = "[0-9]{0,2}";
			string Date = "[0-9]{0,2} [a-zA-Z]{3} [0-9]{2}";
			string ValidChars = "[a-zA-Z0-9:/\\.\\-_ ?!'(),%$&]";

			string SeasonNumber = "(?<SeasonNumber>" + Number + ")";
			string EpisodeNumber = "(?<EpisodeNumber>" + Number + ")";
			string EpisodeTitle = "(?<Title>" + ValidChars + "+)";
			string AirDate = "(?<AirDate>" + Date + ")";

			string StrRegex = Number + "\\.[ ]* " + SeasonNumber + "-[ ]?" + EpisodeNumber + "[ ]*" + "[a-zA-Z0-9]{0,10}" + "[ ]*" + AirDate + "[ ]+<a target=\"_blank\" href=\"" + ValidChars + "+\">" + EpisodeTitle + "</a>"; ;

			Show.Episodes = new Dictionary<string, EpisodeInfo>();
			MatchCollection Collection = Regex.Matches(PageShow, StrRegex);
			foreach (Match M in Collection)
			{
				string SN = M.Groups["SeasonNumber"].Value;
				string EN = M.Groups["EpisodeNumber"].Value;

				EpisodeInfo Info = new EpisodeInfo();
				Info.AirDate = DateTime.Parse(M.Groups["AirDate"].Value);
				Info.Title = M.Groups["Title"].Value;
				Show.Episodes.Add("s" + SN + "e" + EN, Info);
			}

			Show.IsInCache = true;
		}


    }

}


